<template>
  <el-card class="box-card">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row :gutter="20">
      <el-col :span="6"
        ><div class="grid-content bg-purple">
          <el-input
            placeholder="请输入内容"
            v-model="getGoods.query"
            class="input-with-select"
            clearable
            @clear="initList"
            @blur="initList"
            @keydown.enter.native="initList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="initList"
            ></el-button>
          </el-input></div
      ></el-col>
      <el-col :span="2"
        ><div class="grid-content bg-purple">
          <el-button type="primary" plain @click="toAdd">添加商品 </el-button>
        </div></el-col
      >
    </el-row>
    <el-table
      :data="goodsList"
      stripe
      border
      style="width: 100% height:50px"
      v-loading="isLoading"
    >
      <el-table-column type="id" prop="goods_id" label="商品id" width="70">
      </el-table-column>
      <el-table-column prop="goods_name" label="商品名册" width="300">
      </el-table-column>
      <el-table-column
        prop="goods_price"
        label="价格"
        width="70"
      ></el-table-column>
      <el-table-column
        prop="goods_number"
        label="数量"
        width="70"
      ></el-table-column>
      <el-table-column
        prop="goods_weight"
        label="重量"
        width="70"
      ></el-table-column>
      <el-table-column prop="goods_state" label="商品状态">
        <template slot-scope="scope">
          <div :state="scope.row.goods_state">
            {{ scope.row.goods_state | stateTrans }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="add_time" label="添加时间" width="180">
        <template slot-scope="scope">
          <div :addDate="scope.row.add_time">
            {{ scope.row.add_time | formatDate }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="upd_time" label="更新时间" width="180">
        <template slot-scope="scope">
          <div :updataDate="scope.row.add_time">
            {{ scope.row.upd_time | formatDate }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="hot_mumber" label="热销品数量"> </el-table-column>
      <el-table-column prop="is_promote" label="是否热销品">
        <template slot-scope="scope">
          <div :promote="scope.row.is_promote">
            {{ scope.row.is_promote | isHot }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <!-- eslint-disable-next-line -->
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="getEditGood(scope.row)"
            ></el-button>
          </el-tooltip>

          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="delGood(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="getGoods.pagenum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="getGoods.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 编辑商品弹框 -->
    <el-dialog :visible.sync="editShow" width="500px">
      <el-form
        :model="editForm"
        label-width="80px"
        ref="editUserForm"
        :rules="rules"
      >
        <el-form-item label="商品id" prop="id">
          <el-input
            v-model="editForm.id"
            auto-complete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="goods_name">
          <el-input
            v-model="editForm.goods_name"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="goods_price">
          <el-input
            v-model="editForm.goods_price"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="goods_number">
          <el-input
            v-model="editForm.goods_number"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品分类">
          <div class="block">
            <el-cascader
              :value="value"
              :options="options"
              :props="props"
              @change="handleChange"
            ></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="重量" prop="goods_weight">
          <el-input
            v-model="editForm.goods_weight"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="goods_introduce">
          <el-input
            v-model="editForm.goods_introduce"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片路径" prop="pics">
          <el-upload
            action="http://ludir.cn:8888/api/private/v1/goods"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="editForm.pics" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品参数" prop="attrs">
          <el-input
            v-model="editForm.attrs"
            auto-complete="off"
            placeholder="可以写多个,以逗号隔开"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editShow = false">取 消</el-button>
        <el-button type="primary" @click="editGoods('editUserForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getGoodsList,
  getSingleGood,
  getCategoriesList,
  editGoods,
  delGood
} from "@/api/index";
export default {
  data() {
    return {
      isLoading: false,
      // 获取商品列表
      getGoods: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },
      goodsList: [],
      total: 0,
      // 编辑商品
      editShow: false,
      editForm: {
        goods_name: "",
        goods_price: "",
        goods_number: "",
        goods_cat: "",
        goods_weight: "",
        goods_introduce: "",
        pics: "",
        attrs: "",
        id: 0
      },
      // 商品分类列表
      categoriesList: [],
      value: "",
      props: {
        value: "cat_id",
        label: "cat_name"
      },
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      options: [],
      dialogVisible: false,
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 编辑商品
    async getEditGood(row) {
      this.editShow = true;
      await getSingleGood(row.goods_id).then(({ data, meta }) => {
        if (meta.status === 200) {
          this.editForm.goods_name = data.goods_name;
          this.editForm.goods_price = data.goods_price;
          this.editForm.goods_number = data.goods_number;
          this.editForm.goods_cat = data.goods_cat;
          this.editForm.goods_weight = data.goods_weight;
          this.editForm.goods_introduce = data.goods_introduce;
          this.editForm.pics = data.pics;
          this.editForm.attrs = data.attrs;
          this.editForm.id = data.goods_id;
        } else {
          this.$message.warning(meta.msg);
        }
      });
      this.editShow = true;
    },
    async editGoods(formName) {
      await this.$refs[formName].validate(valide => {
        if (valide) {
          editGoods(this.editForm).then(res => {
            if (res.meta.status === 200) {
              this.$message.success("修改成功");
              this.initList();
              this.editShow = false;
            } else {
              this.$message.warning(res.meta.msg);
            }
          });
        }
      });
    },
    // 获取商品列表
    async initList() {
      let {
        data: { goods, pagenum, total }
      } = await getGoodsList({
        params: this.getGoods
      });
      this.goodsList = goods;
      this.total = total;
      this.pagenum = pagenum;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.getGoods.pagesize = val;
      this.initList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.getGoods.pagenum = val;
      this.initList();
    },
    // 删除
    delGood(row) {
      this.$confirm("真的要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let data = await delGood(row.goods_id);
          data.meta.status == 200
            ? this.$message.success(data.meta.msg)
            : this.$message.warning(data.meta.msg);
          this.initList();
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 添加商品页跳转
    toAdd() {
      this.$router.push("toadd");
    },
    handleChange(value) {
      this.editForm.goods_cat = value.join();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      console.log(file);
    },
    handleSuccess(response, file) {
      this.editForm.pics = file.url;
    },
    isEdit(res) {
      this.options = res;
    },
    isDel(res) {
      this.options = res;
    }
  },
  filters: {
    stateTrans(state) {
      switch (state) {
        case 0:
          return "未通过";
        case 1:
          return "审核后";
        case 2:
          return "已审核";
      }
    },
    isHot(state) {
      switch (state) {
        case false:
          return "否";
        case true:
          return "是";
      }
    },
    formatDate(date) {
      let val = new Date(date);
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let min = val.getMinutes();
      let sec = val.getSeconds();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      hour = hour < 10 ? "0" + hour : hour;
      min = min < 10 ? "0" + min : min;
      sec = sec < 10 ? "0" + sec : sec;
      return `${year}-${month}-${day} ${hour}:${min}:${sec}`;
    }
  },
  async created() {
    this.isLoading = true;
    await this.initList();
    this.isLoading = false;

    // 获取商品分类列表
    await getCategoriesList(this.queryInfo).then(({ data, meta }) => {
      if (meta.status == 200) {
        this.categoriesList = data;
        this.options = data;
      } else {
        this.$message.error(meta.msg);
      }
    });
  }
};
</script>

<style>
.home {
  height: 100%;
}
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.el-table {
  line-height: 0;
}
.el-col {
  line-height: 0;
}

.el-pagination {
  margin-top: 40px;
  height: 30px;
}
.el-dialog {
  line-height: 0;
}
.el-select {
  display: block;
}
.el-form-item__label {
  text-align: center;
}
.el-row {
  margin: 20px 0;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
}
</style>
